<script setup>
import {ref} from 'vue'
import axios from 'axios'

const url = 'http://localhost:3000'


let blogs = ref([]);
let blog = ref({
  title:' ',
  author:' '
})

let isShow=ref(false)
let keyword = ref('') 

$(function(){
    axios.get(`${url}/blogs`).then((res=>{
        console.log(res);
        res.data.data.forEach(item=>{
            let html=`
                  <tr class="blog${item.id}">
                    <td>${item.id}</td>
                    <td>${item.title}</td>
                    <td>${item.author}</td>
                    <td>
                        <input type="button" value="编辑" onclick="btn_Edit(${item.id})">
                        <input type="button" value="删除" onclick="btn_Del(${item.id})">
                    </td>
                </tr>
            `

            $('.initList').append(html)
        })
        
    }))
})


function btnDel(id){
  console.log('删除',id);
  // let idx = blogs.value.findIndex(item=>item.id === id )
   
  // blogs.value.splice(idx,1)
  axios.delete(`${url}/blogs/${id}`).then(()=>{
    // fetchBlogs()
  })
}

function btnEdit(id){
  console.log('编辑',id);
  isShow.value=true
}

function btnAdd(){
  console.log('新增');
  isShow.value=true


}

function btnfilter(){
  console.log('查询');
  
  blogs.value=initblogs.filter(item=>item.title.includes(keyword.value))
}

async function btnSave(){
  console.log('保存');
  isShow.value=false
  let id = new URLSearchParams(location.search).get('id') || 0;
    //获取数据
    const title = $('[name=title]').val()
    const author = $('[name=author]').val()


    let res;
    if (id) {
        res = await axios.put(`${url}/blogs/${id}`, { title, author })  //有id，编辑
    } else {
        res = await axios.post(`${url}/blogs`, { title, author })  //没有id，新增
    }

    if (res.data.code === 1000) {
       isShow.value=true
    }
  blogs.value.push(blog.value)
}

function btnCancel(){
  console.log('取消');
  isShow.value=false
}


</script>

<template>
<div class="blogAddOrEdit" v-show="isShow">
  <form>
    <table>
      <tbody>
        <tr>
          <td><label for="">标题：</label></td>
          <td><input type="text" placeholder="请输入标题" v-model="blog.title"></td>
        </tr>
        <tr>
          <td><label for="">作者：</label></td>
          <td><input type="text" placeholder="请输入作者" v-model="blog.author"></td>
        </tr>
        <tr>
          <td><input type="button" value="保存" @click="btnSave"></td>
          <td><input type="button" value="取消" @click="btnCancel"></td>
        </tr>
      </tbody>
    </table>
  </form>
</div>
<div>
  <div>
    <input type="text" placeholder="请输入关键词" v-model="keyword">
    <input type="button" value="查询" @click="btnfilter">
    <input type="button" value="新增" @click="btnAdd">
  </div>
  <table>
    <thead>
      <tr>
        <th>序号</th>
        <th>标题</th>
        <th>作者</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody class="initList">
      
    </tbody>
  </table>
</div>
</template>


